package model

import (
	"context"
	"github.com/zeromicro/go-zero/core/stores/mon"
	"go-admin/base/utils"
	"go.mongodb.org/mongo-driver/bson"
)

var _ MessageModel = (*customMessageModel)(nil)

type (
	// MessageModel is an interface to be customized, add more methods here,
	// and implement the added methods in customMessageModel.
	MessageModel interface {
		messageModel
		InsertMany(ctx context.Context, data []Message) error
		FindManyByFromToId(ctx context.Context, fromToId string) ([]*Message, error)
	}

	customMessageModel struct {
		*defaultMessageModel
	}
)

func (c customMessageModel) FindManyByFromToId(ctx context.Context, fromToId string) ([]*Message, error) {
	var data []*Message
	err := c.conn.Find(ctx, &data, bson.M{"fromToId": fromToId})
	switch err {
	case nil:
		return data, nil
	case mon.ErrNotFound:
		return nil, ErrNotFound
	default:
		return nil, err
	}
}

func (c customMessageModel) InsertMany(ctx context.Context, data []Message) error {
	toAny := utils.ConvertToAny[Message](data)
	_, err := c.conn.InsertMany(ctx, toAny)
	return err
}

// NewMessageModel returns a model for the mongo.
func NewMessageModel(url, db, collection string) MessageModel {
	conn := mon.MustNewModel(url, db, collection)
	return &customMessageModel{
		defaultMessageModel: newDefaultMessageModel(conn),
	}
}
